//获取应用实例
var app = getApp()
var Bmob = require("../../utils/bmob.js");
var common = require('../template/getCode.js')
var that;
var myDate = new Date();
//格式化日期
function formate_data(myDate) {
  let month_add = myDate.getMonth() + 1;
  var formate_result = myDate.getFullYear() + '-' +
    month_add + '-' +
    myDate.getDate()
  return formate_result;
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    notice_status: false,
    accounts: ["微信号", "QQ号", "手机号"],
    accountIndex: 0,
    peopleHide: false,
    isAgree: false,
    date: formate_data(myDate),
    address: '点击选择位置',
    longitude: 0, //经度
    latitude: 0, //纬度
    showTopTips: false,
    TopTips: '',
    noteMaxLen: 200, //备注最多字数
    content: "",
    noteNowLen: 0, //备注当前字数
    types: ["运动", "游戏", "交友", "旅行", "读书", "竞赛", "电影", "音乐", "其他"],
    typeIndex: "0",
    showInput: false, //显示输入真实姓名,
    checked: false,
    quality: 0.2, //图片压缩质量
    isLogin: false
  },
  //活动名称输入事件
  actNameInput(e) {
    that = this
    var actTitle = e.detail.value
    wx.cloud.callFunction({
      name: 'msgSecCheck',
      data: {
        content: actTitle
      }
    }).then(res => {
      if (res.result.errCode == '0') {
        that.setData({
          actTitle: actTitle
        })
      }
      else if (res.result.errCode == '87014') {
        wx.showToast({
          title: '名称违规，请重新编辑',
          icon: 'none',
          duration: 2000
        })
        that.setData({
          actTitle: ""
        })
      }
    })
  },
  showNotice: function (e) {
    wx.navigateTo({
      url: '/pages/protocol/protocol',
    })
  },

  //字数改变触发事件
  bindTextAreaChange: function (e) {
    that = this
    var value = e.detail.value,
      len = parseInt(value.length);
    if (len > that.data.noteMaxLen)
      return;
    that.setData({
      content: value,
      noteNowLen: len
    })
    var actContent = e.detail.value
    wx.cloud.callFunction({
      name: 'msgSecCheck',
      data: {
        content: actContent
      }
    }).then(res => {
      if (res.result.errCode == '0') {
        that.setData({
          actContent: actContent
        })
      }
      else if (res.result.errCode == '87014') {
        wx.showToast({
          title: '内容违规，请重新编辑',
          icon: 'none',
          duration: 2000
        })
        that.setData({
          actContent: ""
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    

    // wx.setStorageSync('nowDate', formate_data(myDate))
    that.setData({ //初始化数据
      src: "",
      isSrc: false,
      ishide: "0",
      autoFocus: true,
      isLoading: false,
      loading: true,
      isdisabled: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.hideToast()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    that = this
    var myInterval = setInterval(getReturn, 500); ////半秒定时查询
    function getReturn() {
      wx.getStorage({
        key: 'user_openid',
        success: function (ress) {
          if (ress.data) {
            clearInterval(myInterval)
            that.setData({
              loading: true
            })
          }
        }
      })
    }
    //判断是否显示登录弹窗
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            isLogin: false
          })
          console.log("if getset", res)
        } else {
          that.setData({
            isLogin: true
          })
          console.log("else getset")
        }
      }
    })
  },

  //上传活动图片
  uploadPic: function () { //选择图标
    var that = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], //压缩图
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (result) {
        wx.showLoading({
          title: '图片上传中',
          mask: true
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var filePath = result.tempFilePaths[0]
        that.setData({
          isSrc: true,
          src: filePath
        })
        //图片质量压缩
        wx.getImageInfo({
          src: filePath,
          success: function (res) {
            that.setData({
              cWidth: res.width,
              cHeight: res.height
            })
            that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality, function (res) {
              //上传图片至腾讯云存储空间
              var timestamp = Date.parse(new Date()); //时间戳,避免重复文件名
              const cloudPath = timestamp + res.tempFilePath.match(/\.[^.]+?$/)[0]
              wx.cloud.uploadFile({
                cloudPath,
                filePath, // 文件路径
                success: res => {
                  // get resource ID
                  console.log(res.fileID, 888)
                  that.setData({
                    actSrc: res.fileID
                  })
                  wx.hideLoading()
                  wx.showToast({
                    title: '上传成功',
                  })
                },
                fail: err => {
                  wx.hideLoading()
                  wx.showToast({
                    title: '上传失败',
                  })
                  // handle error
                }
              })
            });
          }
        })

      }
    })
  },
  //全屏展示封面图片
  showPic: function() {
    wx.previewImage({
      urls: [that.data.src],
    })
  },
  //全屏展示群二维码图片
  showCodePic: function() {
    wx.previewImage({
      urls: [that.data.codeSrc],
    })
  },
  //删除图片
  clearPic: function () { //删除图片
    that.setData({
      isSrc: false,
      src: ""
    })
  },

  //上传活动群二维码
  uploadCodePic: function () { //选择图标
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], //压缩图
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (result) {
        wx.showLoading({
          title: '图片上传中',
          mask: true
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var filePath = result.tempFilePaths[0]
        that.setData({
          isCodeSrc: true,
          codeSrc: filePath
        })
        wx.getImageInfo({
          src: filePath,
          success: function (res) {
            that.setData({
              cWidth: res.width,
              cHeight: res.height
            })
            that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality, function (res) {
              //上传图片至腾讯云存储空间
              var timestamp = Date.parse(new Date()); //时间戳,避免重复文件名
              const cloudPath = timestamp + res.tempFilePath.match(/\.[^.]+?$/)[0]
              wx.cloud.uploadFile({
                cloudPath,
                filePath, // 文件路径
                success: res => {
                  // get resource ID
                  console.log(res.fileID, 888)
                  that.setData({
                    codeSrc1: res.fileID
                  })
                  wx.hideLoading()
                  wx.showToast({
                    title: '上传成功'
                  })
                },
                fail: err => {
                  wx.hideLoading()
                  wx.showToast({
                    title: '上传失败',
                  })
                  // handle error
                }
              })
            });
          }
        })

      }
    })
  },

  //删除活动群二维码
  clearCodePic: function () {
    that.setData({
      isCodeSrc: false,
      codeSrc: ""
    })
  },

  //限制人数
  switch1Change: function (e) {
    if (e.detail.value == false) {
      this.setData({
        peopleHide: false
      })
    } else if (e.detail.value == true) {
      this.setData({
        peopleHide: true
      })
    }
  },

  //改变时间
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  //改变活动类别
  bindTypeChange: function (e) {
    this.setData({
      typeIndex: e.detail.value
    })
  },
  //选择地点
  addressChange: function (e) {
    this.addressChoose(e);
  },
  addressChoose(e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          address: res.name,
          longitude: res.longitude, //经度
          latitude: res.latitude, //纬度
        })
        if (e.detail && e.detail.value) {
          this.data.address = e.detail.value;
        }
      },
      fail: function (e) {
        console.log("fail", e)
      },
      complete: function (e) {
        console.log("complete", e)
      }
    })
  },

  //改变联系方式
  bindAccountChange: function (e) {
    this.setData({
      accountIndex: e.detail.value
    })
  },

  //同意相关条例
  bindAgreeChange: function (e) {
    this.setData({
      isAgree: !!e.detail.value.length,
      showInput: !this.data.showInput
    });
  },

  //表单验证
  showTopTips: function () {
    var that = this;
    this.setData({
      showTopTips: true
    });
    setTimeout(function () {
      that.setData({
        showTopTips: false
      });
    }, 3000);
  },
  //提交表单
  submitForm: function (e) {
    that = this;

    if (that.data.showInput == false) {
      wx.showModal({
        title: '提示',
        content: '请先阅读《发起须知》'
      })
      return;
    }

    var endtime = this.data.date;
    var typeIndex = this.data.typeIndex;
    var acttype = 1 + parseInt(typeIndex);
    var acttypename = getTypeName(acttype); //获得类型名称
    var address = this.data.address;
    var longitude = this.data.longitude; //经度
    var latitude = this.data.latitude; //纬度
    var switchHide = e.detail.value.switchHide;
    var peoplenum = e.detail.value.peoplenum;
    console.log(peoplenum, 666);
    //------发布者真实信息------
    var realname = e.detail.value.realname;
    var contactindex = this.data.accountIndex;
    if (contactindex == 0) {
      var contactWay = "微信号";
    } else if (contactindex == 1) {
      var contactWay = "QQ号";
    } else if (contactindex == 2) {
      var contactWay = "手机号";
    }
    var contactValue = e.detail.value.contactValue;
    var wxReg = new RegExp("^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$");
    var qqReg = new RegExp("[1-9][0-9]{4,}");
    var phReg = /^1[34578]\d{9}$/;
    var nameReg = new RegExp("^[\u4e00-\u9fa5]{2,4}$");
    //先进行表单非空验证
    if (that.data.actTitle == "" || e.detail.value.title == "") {
      this.setData({
        showTopTips: true,
        TopTips: '活动名称空或违规'
      });
    } else if (address == '点击选择位置') {
      this.setData({
        showTopTips: true,
        TopTips: '请选择地点'
      });
    } else if (switchHide == true && peoplenum == "") {
      this.setData({
        showTopTips: true,
        TopTips: '请输入人数'
      });
    } else if (that.data.actContent == "" || e.detail.value.content == "") {
      this.setData({
        showTopTips: true,
        TopTips: '活动内容空或违规'
      });
    } else if (realname == "") {
      this.setData({
        showTopTips: true,
        TopTips: '请输入真实姓名'
      });
    } else if (realname != "" && !nameReg.test(realname)) {
      this.setData({
        showTopTips: true,
        TopTips: '真实姓名一般为2-4位汉字'
      });
    } else if (contactValue == "") {
      this.setData({
        showTopTips: true,
        TopTips: '请输入联系方式'
      });
    } else if (contactWay == "微信号" && !wxReg.test(contactValue)) {
      this.setData({
        showTopTips: true,
        TopTips: '微信号格式不正确'
      });
    } else if (contactWay == "手机号" && !phReg.test(contactValue)) {
      this.setData({
        showTopTips: true,
        TopTips: '手机号格式不正确'
      });
    } else if (contactWay == "QQ号" && !qqReg.test(contactValue)) {
      this.setData({
        showTopTips: true,
        TopTips: 'QQ号格式不正确'
      });
    } else {
      console.log('校验完毕');
      that.setData({
        isLoading: true,
        isdisabled: true
      })
      //向 Events 表中新增一条数据
      wx.getStorage({
        key: 'user_id',
        success: function (ress) {
          var Diary = Bmob.Object.extend("Events");
          var diary = new Diary();
          var me = new Bmob.User();
          me.id = ress.data;
          diary.set("title", that.data.actTitle);
          diary.set("endtime", endtime);
          diary.set("acttype", acttype + "");
          diary.set("isShow", 1);
          diary.set("address", address);
          diary.set("longitude", longitude); //经度
          diary.set("latitude", latitude); //纬度\
          if (that.data.peopleHide) { //如果设置了人数
            diary.set("peoplenum", peoplenum);
          } else if (!that.data.peopleHide) {
            diary.set("peoplenum", "-1");
          }
          diary.set("content", that.data.actContent);
          diary.set("publisher", me);
          diary.set("likenum", 0);
          diary.set("commentnum", 0);
          diary.set("liker", []);
          diary.set("joinnumber", 0); //发布后初始加入人数为0
          diary.set("joinArray", []);
          if (that.data.isSrc == true) {
            var actpic = that.data.actSrc;
            diary.set("actpic", actpic);
          }
          //新增操作
          diary.save(null, {
            success: function (result) {
              var Diary = Bmob.Object.extend("EventMore");
              var query = new Diary();
              var Events = Bmob.Object.extend("Events");
              var event = new Events();
              event.id = result.id;
              query.set("Status", 0);
              query.set("Statusname", "准备中");
              query.set("event", event);
              //如果上传了群二维码
              if (that.data.isCodeSrc == true) {
                var codeSrc = that.data.codeSrc1; //图片云存储路径
                query.set("qrcode", codeSrc);
              }
              query.save();

              //将发布者的信息添加到联系表中
              wx.getStorage({
                key: 'user_id',
                success: function (ress) {
                  var Contacts = Bmob.Object.extend("Contacts");
                  var contact = new Contacts();
                  var Events = Bmob.Object.extend("Events");
                  var event = new Events();
                  event.id = result.id;
                  var me = new Bmob.User();
                  me.id = ress.data;
                  contact.set("publisher", me); //发布人是自己
                  contact.set("currentUser", me); //参加的人也是自己
                  contact.set("event", event);
                  contact.set("realname", realname);
                  contact.set("contactWay", contactWay);
                  contact.set("contactValue", contactValue);
                  contact.save();
                },
              })
              console.log("发布成功,objectId:" + result.id);
              var eventIdd = result.id
              wx.setStorage({
                key: 'eventIdd',
                data: result.id,
              })
              that.setData({
                isLoading: false,
                isdisabled: false,
                eventId: result.id,
              })
              //上传活动信息至云开发数据库用作模糊搜索(Events表云开发，bmob数据库各一份)
              wx.getStorage({
                key: 'eventIdd',
                success: function (res) {
                  var eventIdd = res.data
                },
              })
              var user_id = wx.getStorageSync("user_id")
              //获取当前登录用户
              var currentUser = Bmob.User.current();
              var nickName = currentUser.attributes.nickname;
              var avatarUrl = currentUser.attributes.userPic;
              const db = wx.cloud.database()
              db.collection('Events').add({
                data: {
                  actpic: that.data.actSrc, //活动图片
                  title: that.data.actTitle, //活动标题
                  content: that.data.actContent, //活动内容
                  endtime: endtime, //有效时间
                  address: address, //活动地址
                  acttype: Number(acttype), //活动类型id
                  acttypename: acttypename, //活动名称
                  id: eventIdd, //活动id，用作bmob跳转活动详情页
                  _id: eventIdd, //用作修改信息
                  nickName: nickName,
                  avatarUrl: avatarUrl,
                  createTime: db.serverDate(),
                  publisherId: user_id,
                  isShow: 1
                }
              }).then(res => {
                console.log(res, "备份成功")
              }).catch(err => {
                return err
              })
              console.log(eventIdd, 333)

              //添加成功，返回成功之后的objectId(注意，返回的属性名字是id,而不是objectId)
              common.dataLoading("发起成功", "success", function () {
                // debugger
                //重置表单
                that.setData({
                  title: '',
                  typeIndex: 0,
                  address: '点击选择位置',
                  longitude: 0, //经度
                  latitude: 0, //纬度
                  date: formate_data(myDate),
                  isHide: true,
                  checked: false,
                  peoplenum: 0,
                  peopleHide: false,
                  isAgree: false,
                  accountIndex: 0,
                  realname: "",
                  content: "",
                  contactValue: '',
                  noteNowLen: 0,
                  showInput: false,
                  src: "",
                  isSrc: false,
                  codeSrc: "",
                  isCodeSrc: false

                })
              });
            },
            error: function (result, error) {
              //添加失败
              console.log("发布失败=" + error);
              common.dataLoading("发起失败", "loading");
              that.setData({
                isLoading: false,
                isdisabled: false
              })
            }
          })
        },
      })
    }
    setTimeout(function () {
      that.setData({
        showTopTips: false
      });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 质量压缩
   */
  getCanvasImg(tempFilePaths, canvasWidth, canvasHeight, quality, callback) {
    var that = this;
    const ctx = wx.createCanvasContext('attendCanvasId');
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.drawImage(tempFilePaths[0], 0, 0, canvasWidth, canvasHeight);
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'attendCanvasId',
        fileType: 'jpg',
        quality: quality,
        success: function success(res) {
          callback && callback(res)
        },
        fail: function (e) {
          wx.showToast({
            title: '图片上传失败，请重新上传！',
            icon: 'none'
          })
        }
      });
    });
  },
  //调用app.js onLaunch方法注册用户信息
  getUserInfo() {
    this.setData({
      isLogin: false
    })
    app.onLaunch()
  },
})

//根据活动类型获取活动类型名称
function getTypeName(acttype) {
  var acttypeName = "";
  if (acttype == 1) acttypeName = "运动";
  else if (acttype == 2) acttypeName = "游戏";
  else if (acttype == 3) acttypeName = "交友";
  else if (acttype == 4) acttypeName = "旅行";
  else if (acttype == 5) acttypeName = "读书";
  else if (acttype == 6) acttypeName = "竞赛";
  else if (acttype == 7) acttypeName = "电影";
  else if (acttype == 8) acttypeName = "音乐";
  else if (acttype == 9) acttypeName = "其他";
  return acttypeName;
}